<template>
  <basic-container>
    <div class="container-body">
      <el-form :inline="true" :model="query" class="demo-form-inline">
        <el-form-item label="关键词">
          <el-input size="small" v-model="query.keyword" placeholder="关键词" clearable></el-input>
        </el-form-item>
        <el-form-item label="发布日期">
          <el-date-picker v-model="query.publishDates" type="daterange" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width:240px;">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" icon="el-icon-search" @click="onSearch" :loading="loading">搜索
          </el-button>
          <el-button size="small" icon="el-icon-delete" @click="searchReset" :loading="loading">清空</el-button>
        </el-form-item>
      </el-form>
      <div class="btn-operate">
        <el-button @click="showAddView" type="primary" size="small" icon="el-icon-plus">
          新增
        </el-button>
      </div>
      <el-table header-row-class-name="container-table-header" :data="data" size="small" style="width: 100%;margin-bottom: 20px;"
                row-key="id" border stripe v-loading="loading" @cell-click="handleCellClick">
        <el-table-column prop="title" label="标题">
        </el-table-column>
        <el-table-column prop="analysis" label="解读" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="source" label="来源">
        </el-table-column>
        <el-table-column prop="publishDate" label="发布日期">
        </el-table-column>
        <el-table-column label="操作" width="170">
          <template slot-scope="scope">
            <el-button v-if="permissions.knowledge_get" type="text" size="small" icon="el-icon-view" @click="showViewBox(scope.row)">查看
            </el-button>
            <el-button v-if="permissions.knowledge_add" type="text" size="small" icon="el-icon-edit" @click="showEditBox(scope.row)">编辑
            </el-button>
            <el-button v-if="permissions.knowledge_del" type="text" size="small" icon="el-icon-delete" @click="handleDelete(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="container-page">
        <el-pagination
          @size-change="sizeChange"
          @current-change="currentChange"
          :current-page="page.current"
          :page-sizes="[10, 20, 30, 40, 50, 100]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total">
        </el-pagination>
      </div>
    </div>
    <el-dialog :title="formTitle" fullscreen custom-class="ledger" :visible.sync="formBox" :close-on-click-modal="!formBox" :append-to-body="true" :before-close="resetForm" width="1200px" top="5vh">
      <div class="title">基础信息</div>
      <el-form ref="optForm" :model="form" label-width="90px">
        <el-row :gutter="10">
          <el-col :span="18">
            <el-form-item label="标题" prop="title" :rules="{required: true, message: '标题不能为空', trigger: ['blur', 'change']}">
              <el-input placeholder="标题" clearable v-model="form.title"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item llabel="发布日期" prop="publishDate" :rules="{required: true, message: '发布日期不能为空', trigger: ['blur', 'change']}">
              <el-date-picker v-model="form.publishDate" type="date" placeholder="发布日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="来源" prop="source">
          <el-input placeholder="来源" clearable v-model="form.source"/>
        </el-form-item>
        <el-form-item label="解读" prop="analysis" :rules="{required: true, message: '解读不能为空', trigger: ['blur', 'change']}">
          <el-input placeholder="解读" clearable v-model="form.analysis" type="textarea" :rows="2"/>
        </el-form-item>
        <el-form-item label="依据" prop="source">
          <el-input placeholder="依据" clearable v-model="form.according" type="textarea" :rows="2"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm" size="small" icon="el-icon-close">关闭</el-button>
        <el-button v-if="!isView" type="primary" @click="submit" size="small" icon="el-icon-check">保存</el-button>
      </span>
    </el-dialog>

    <el-dialog title="查看" custom-class="ledger" :visible.sync="viewBox"
               :append-to-body="true" :before-close="resetForm" width="1200px" top="5vh">
      <div class="title">基本信息</div>
      <el-descriptions title="" :labelStyle="{'width': '80px'}">
        <el-descriptions-item label="标题" :span="2">{{ form.title }}</el-descriptions-item>
        <el-descriptions-item label="发布日期">{{ form.publishDate }}</el-descriptions-item>
        <el-descriptions-item label="来源" :span="3">{{ form.source }}</el-descriptions-item>
        <el-descriptions-item label="解读" :span="3">{{ form.analysis }}</el-descriptions-item>
        <el-descriptions-item label="依据" :span="3">{{ form.according }}</el-descriptions-item>
      </el-descriptions>
      <span slot="footer">
        <el-button @click="resetForm" size="small" icon="el-icon-close">关闭</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
import {mapGetters} from "vuex";
import Tinymce from '@/components/Tinymce'
import print from 'vue-print-nb'
import {delObj, fetchList, getObj, submit} from "@/api/adis/base/knowledge";

export default {
  directives: {
    print
  },
  components: {
    Tinymce,
  },
  dictTypes: [],
  data() {
    return {
      ls:{
        'background': 'white'
      },
      importBox: false,
      isEdit: false,
      isView: false,
      viewBox: false,
      formBox: false,
      formTitle: '',
      loading: false,
      query: {},
      form: {
        renterName: '',
        freeRentMonth: 0,
        totalCopies: 4,
        jfCopies: 3,
        moneyRentDeposits: [],
        value1: '',
        value2: '',
      },
      page: {
        size: 10,
        current: 1,
        total: 0
      },
      data: [],
      printBox: false,
      print: {
        id: 'printArea',
        popTitle: '', // 打印配置页上方标题
        extraHead: '', //最上方的头部文字，附加在head标签上的额外标签,使用逗号分隔
        preview: '', // 是否启动预览模式，默认是false（开启预览模式，可以先预览后打印）
        previewTitle: '', // 打印预览的标题（开启预览模式后出现）,
        previewPrintBtnLabel: '', // 打印预览的标题的下方按钮文本，点击可进入打印（开启预览模式后出现）
        zIndex: '', // 预览的窗口的z-index，默认是 20002（此值要高一些，这涉及到预览模式是否显示在最上面）
        previewBeforeOpenCallback() {}, //预览窗口打开之前的callback（开启预览模式调用）
        previewOpenCallback() {}, // 预览窗口打开之后的callback（开启预览模式调用）
        beforeOpenCallback() {}, // 开启打印前的回调事件
        openCallback() {}, // 调用打印之后的回调事件
        closeCallback() {}, //关闭打印的回调事件（无法确定点击的是确认还是取消）
        url: '',
        standard: '',
        extraCss: '',
      },
      selectionRow: [],
      Authorization: '',
      fileList: [], // 文件
    }
  },
  computed: {
    ...mapGetters(["permissions"])
  },
  created() {
    this.onLoad(this.page);
    this.Authorization = 'Bearer ' + this.$store.getters.access_token
  },
  methods: {
    handleCellClick(row, column) {
      if (row && column.label !== "操作"){
        this.showViewBox(row)
      }
    },

    submit() {
      this.$refs['optForm'].validate((valid) => {
        if (valid) {
          this.fileList && this.fileList.map((file) => {
            this.form.fileUrl = file.response ? file.response.data.url : file.url
          });
          this.loading = true;
          submit(this.form).then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.resetForm();
            this.onLoad(this.page);
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    showAddView() {
      this.formTitle = '新增';
      this.formBox = true;
      this.form = {};
    },
    showEditBox(row) {
      getObj(row.knowledgeId).then((res) => {
        this.form = res.data.data;
        if(res.data.data.fileUrl) {
          this.fileList.push({url:res.data.data.fileUrl});
        }
        this.formTitle = '编辑';
        this.formBox = true;
        this.isEdit = true;
      });
    },
    showViewBox(row) {
      getObj(row.knowledgeId).then((res) => {
        this.form = res.data.data;
        this.viewBox = true;
        this.isView = true;
      });
    },
    handleDelete(row) {
      this.$confirm("确定将选择的数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return delObj(row.knowledgeId);
      })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    resetForm() {
      this.formBox = false;
      this.viewBox = false;
      this.isEdit = false;
      this.isView = false;
      this.form = {};
      this.formTitle = '';
      this.$refs['optForm'] && this.$refs['optForm'].resetFields();
      this.viewBox = false;
      this.printBox = false;
    },
    onSearch() {
      this.page.current = 1;
      this.onLoad(this.page);
    },
    searchReset() {
      this.query = {};
      this.page.current = 1;
      this.onLoad(this.page);
    },
    currentChange(current) {
      this.page.current = current;
      this.onLoad(this.page);
    },
    sizeChange(size) {
      this.page.size = size;
      this.onLoad(this.page);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      if(this.query.publishDates) {
        this.query.startDate = this.query.publishDates[0];
        this.query.endDate = this.query.publishDates[1];
      }
      fetchList(Object.assign(params, this.query, page)).then(res => {
        this.loading = false;
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
      }, () => {
        this.loading = false;
      });
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
    },
    handleSuccess(response, file, fileList) {
      this.fileList = fileList;
    },
    handlePreview(file) {
      window.open(file.url ? file.url : file.response.data.url)
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
  }
};
</script>

<style>
</style>
